package priv.mill.clien;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import priv.mill.net.MyHttp;

public class MyEncoder extends MessageToByteEncoder<MyHttp>{

	@Override
	protected void encode(ChannelHandlerContext ctx, 
			MyHttp msg, ByteBuf out)
			throws Exception {
		byte[] bytes = toBytes(msg);
		out.writeInt(bytes.length);
		out.writeBytes(bytes);
	}

	private byte[] toBytes(MyHttp msg) throws IOException {
		try (ByteArrayOutputStream stream = new ByteArrayOutputStream();
				ObjectOutputStream outputStream = new ObjectOutputStream(stream);){
			outputStream.writeObject(msg);
			return stream.toByteArray();
		} 
	}

}
